package com.app.newcsc.fragment.main;

import android.app.Application;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import androidx.annotation.NonNull;

import com.app.newcsc.app.AppApplication;
import com.app.newcsc.data.DemoRepository;
import com.app.newcsc.entity.ShopTokenEntity;
import com.app.newcsc.entity.UserEntity;
import com.app.newcsc.entity.UserInfoEntity;
import com.app.newcsc.fragment.my.active.ActiveFragment;
import com.app.newcsc.fragment.my.exchangepoints.ExchangePointsFragment;
import com.app.newcsc.fragment.my.level.LevelUpFragment;
import com.app.newcsc.fragment.my.paytype.PayTypeFragment;
import com.app.newcsc.fragment.my.problem.ProblemFragment;
import com.app.newcsc.fragment.my.safe.SafeFragment;
import com.app.newcsc.fragment.my.set.SetFragment;
import com.app.newcsc.fragment.my.task.TaskFragment;
import com.app.newcsc.http.response.ApiException;
import com.app.newcsc.utils.ShareUtil;
import com.app.newcsc.utils.TextUtil;
import com.app.newcsc.utils.Utils;

import java.util.HashMap;
import java.util.Map;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.observers.DisposableObserver;
import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent;
import me.goldze.mvvmhabit.http.BaseResponse;
import me.goldze.mvvmhabit.http.ResponseThrowable;
import me.goldze.mvvmhabit.utils.RxUtils;
import me.goldze.mvvmhabit.utils.ToastUtils;

/**
 * @author: woking
 * @date: 2021/6/8
 * @description：
 */
public class MyViewModel extends BaseViewModel<DemoRepository>
{
    //使用Observable
    public SingleLiveEvent<Boolean> requestCameraPermissions = new SingleLiveEvent<>();
    //使用LiveData
    public SingleLiveEvent<String> loadUrlEvent = new SingleLiveEvent<>();

    public SingleLiveEvent<UserEntity> mUserInfoEntity = new SingleLiveEvent<>();

//    public MyViewModel(@NonNull Application application) {
//        super(application);
//    }
    public MyViewModel(@NonNull Application application, DemoRepository repository)
    {
        super(application, repository);
    }
    public void taskClick(View v)//任务包
    {
        if(!Utils.isLogin())
        {
            return;
        }
        Log.e("TAG","============taskClick=============");
        startContainerActivity(TaskFragment.class.getCanonicalName());
    }

    //兑换积分
    public BindingCommand exchange_pointsClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            if(!Utils.isLogin())
            {
                return;
            }
            Bundle bundle = new Bundle();
            bundle.putString("type","AD");
            startContainerActivity(ExchangePointsFragment.class.getCanonicalName(),bundle);
            Log.e("TAG","============taskClick=============");
        }
    });
    //活跃指数
    public BindingCommand activeClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            if(!Utils.isLogin())
            {
                return;
            }
            startContainerActivity(ActiveFragment.class.getCanonicalName());
        }
    });
    //等级提升
    public BindingCommand levelUpClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            if(!Utils.isLogin())
            {
                return;
            }
            startContainerActivity(LevelUpFragment.class.getCanonicalName());
        }
    });

    //安全中心
    public BindingCommand safeClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            if(!Utils.isLogin())
            {
                return;
            }
//            startActivity(ViewPagerActivity.class);
            startContainerActivity(SafeFragment.class.getCanonicalName());
        }
    });
    //收款方式
    public BindingCommand paymentClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            if(!Utils.isLogin())
            {
                return;
            }
            startContainerActivity(PayTypeFragment.class.getCanonicalName());
        }
    });
    //set
    public BindingCommand setClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            startContainerActivity(SetFragment.class.getCanonicalName());
        }
    });
    //problem
    public BindingCommand problemClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            startContainerActivity(ProblemFragment.class.getCanonicalName());
        }
    });


    public void requestNetWork() {
        Log.e("TAG","==========requestNetWork======otcConfig=======");
        //可以调用addSubscribe()添加Disposable，请求与View周期同步
        HashMap<String, Object> map = new HashMap<>();
//        lang=zh-cn
        map.put("lang","zh-cn");
        model.userInfo(map)
                .compose(RxUtils.schedulersTransformer()) //线程调度
                .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
                .doOnSubscribe(this)//请求与ViewModel周期同步
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
//                        showDialog("正在请求...");
                    }
                })
                .subscribe(new DisposableObserver<BaseResponse<UserInfoEntity>>() {
                    @Override
                    public void onNext(BaseResponse<UserInfoEntity> response) {
                        if(response.getCode() == 200)
                        {
                            Log.e("TAG", "=======userInfo================"+response.getData().mobile_hide);
//                            mUserInfoEntity.postValue(response.getData());
                        }
//                        //清除列表
//                        observableList.clear();
//                        //请求成功
//                        if (response.getCode() == 1) {
//                            for (DemoEntity.ItemsEntity entity : response.getResult().getItems()) {
//                                TransactionTabItemViewModel itemViewModel = new TransactionTabItemViewModel(TransactionTabViewModel.this, entity);
//                                //双向绑定动态添加Item
//                                observableList.add(itemViewModel);
//                            }
//                        } else {
//                            //code错误时也可以定义Observable回调到View层去处理
//                            ToastUtils.showShort("数据错误");
//                        }
                    }

                    @Override
                    public void onError(Throwable throwable) {
                        Log.e("TAG","==========requestNetWork======otcConfig===onError====");
                        //关闭对话框
//                        dismissDialog();
//                        //请求刷新完成收回
//                        uc.finishRefreshing.call();
//                        if (throwable instanceof ResponseThrowable) {
//                            ToastUtils.showShort(((ResponseThrowable) throwable).message);
//                        }
                    }

                    @Override
                    public void onComplete() {
                        Log.e("TAG","==========requestNetWork======otcConfig===onComplete====");
                        //关闭对话框
//                        dismissDialog();
                        //请求刷新完成收回
//                        uc.finishRefreshing.call();
                    }
                });
    }

    public void baseUser() {
        Log.e("TAG","==========baseUser=============");
        model.baseUser()
                .compose(RxUtils.schedulersTransformer()) //线程调度
                .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
                .doOnSubscribe(this)//请求与ViewModel周期同步
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        showDialog("正在请求...");
                    }
                })
                .subscribe(new DisposableObserver<BaseResponse<UserEntity>>() {
                    @Override
                    public void onNext(BaseResponse<UserEntity> response) {
                        Log.e("TAG","================baseUser===onNext====");
                        if(null != response && null != response.getData())
                        {
                            mUserInfoEntity.postValue(response.getData());
                            AppApplication.ad_exchange_level = response.getData().ad_exchange_level;
                            ((AppApplication)AppApplication.getInstance()).setUserEntity(response.getData());
                        }
                    }

                    @Override
                    public void onError(Throwable throwable) {
                        Log.e("TAG","================baseUser===onError===="+throwable.getMessage());
                        if (throwable instanceof ResponseThrowable) {
                            String msg = ApiException.getShowmessage(((ResponseThrowable) throwable).errorBody);
                            int code = ((ResponseThrowable) throwable).code;
                            if((!TextUtil.isEmpty(msg) && msg.contains("被禁")) || code == 403)
                            {
                                if(TextUtil.isEmpty(AppApplication.userJinYongMsg))
                                {
                                    AppApplication.userJinYongMsg = msg;
                                }
                                ToastUtils.showShortSafe(msg);
                            }
                            else
                            {
                                if(!TextUtil.isEmpty(AppApplication.userJinYongMsg))
                                {
                                    AppApplication.userJinYongMsg = "";
                                }
                            }

                        }
                        dismissDialog();

                        walletCoins();
                    }

                    @Override
                    public void onComplete() {
                        Log.e("TAG","================baseUser===onComplete====");
                        if(!TextUtil.isEmpty(AppApplication.userJinYongMsg))
                        {
                            AppApplication.userJinYongMsg = "";
                        }
                        dismissDialog();

                        walletCoins();
                    }
                });
    }
    public void getZTXShopToken()
    {
        Log.e("TAG","============getZTXShopToken=============");
        if(((AppApplication)AppApplication.getInstance()).getUserEntity() == null)
        {
            return;
        }
        model.getZTXShopToken(((AppApplication)AppApplication.getInstance()).getUserEntity().mobile)
//        model.getCSCToken(token)
                .compose(RxUtils.schedulersTransformer()) //线程调度
                .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
                .doOnSubscribe(this)//请求与ViewModel周期同步
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
//                        showDialog("正在请求...");
                    }
                })
                .subscribe(new DisposableObserver<BaseResponse<ShopTokenEntity>>() {
                    @Override
                    public void onNext(BaseResponse<ShopTokenEntity> response) {
                        Log.e("TAG","============getZTXShopToken==========onNext===");
                        if(null != response && null != response.getData())
                        {
                            ShareUtil.getInstance().save(ShareUtil.ZTX_SHOP_TOKEN , response.getData().token_type+" " + response.getData().access_token);
                        }
                    }
                    @Override
                    public void onError(Throwable throwable) {
                        Log.e("TAG","============getZTXShopToken======onError======="+throwable.getMessage());
//                        if (throwable instanceof ResponseThrowable) {
//                            ToastUtils.showShortSafe(((ResponseThrowable) throwable).message);
//                        }
                    }
                    @Override
                    public void onComplete() {
                        Log.e("TAG","============getZTXShopToken=======onComplete======");
                    }
                });
    }

    /**
     * 钱包类型
     */
    public void walletCoins()
    {
        int map = ((AppApplication)AppApplication.getInstance()).getWalletCoinsNun();
        if(map > 0)
        {
            return;
        }
        model.walletCoins()
                .compose(RxUtils.schedulersTransformer()) //线程调度
                .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
                .doOnSubscribe(this)//请求与ViewModel周期同步
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
//                        showDialog("正在请求...");
                    }
                })
                .subscribe(new DisposableObserver<Map<String,String>>() {
                    @Override
                    public void onNext(Map<String,String> response) {
                        Log.e("TAG","============walletCoins=====onNext========");
                        if(null != response)
                        {
//                            Log.e("TAG","============walletCoins=====onNext=====1111===");
                            if(response.size() > 0)
                            {
                                ((AppApplication)AppApplication.getInstance()).clearWalletCoins();
                                for (Map.Entry<String, String> entry : response.entrySet())
                                {
//                                    Log.e("TAG","============walletCoins=====onNext=====222222===Key = " + entry.getKey() + ", Value = " + entry.getValue());
                                    ((AppApplication)AppApplication.getInstance()).addWalletCoins(entry.getValue(),entry.getKey());
                                }
                            }
                        }
                    }
                    @Override
                    public void onError(Throwable throwable) {
                        Log.e("TAG","============walletCoins=====onError========"+throwable.getMessage());
//                        if (throwable instanceof ResponseThrowable) {
//                            ToastUtils.showShortSafe(((ResponseThrowable) throwable).message);
//                        }
//                        dismissDialog();
                    }
                    @Override
                    public void onComplete() {
                        Log.e("TAG","============walletCoins=====onComplete========");
//                        dismissDialog();
                    }
                });
    }
}